<?php 
namespace town\base;

class Container
{
	private static $obj = null;
    private $map = null;

    public function __construct()
	{
		$this->map = [];
    }

    /**
     * 负责初始化容器
     */
    private function get($name)
    {
		$obj = $this->map[$name];
		if ($obj) {
			return $obj;
		}

    	// TODO::添加服务
    	// 1.构造函数有参数(配置项),如db服务
    	// 2.构造函数没有参数,简单实例化就行
        try {
            $ref_class = new \ReflectionClass($name);
        } catch (Exception $e) {
            throw new ReflectionException("Class request does not exist $name", 1);
        }
		$obj = $ref_class->newInstance();
		$this->map[$name] = $obj;
		return $obj;
    }
	
	public function __set($name, $value)
	{
		$this->map[$name] = $value;
	}

	public function __get($name)
	{
		return $this->map[$name];
	}	

    public function __call($method, $arguments)
    {
        if (method_exists($this, $method)) {
            return call_user_func_array([$this, $method], $arguments);
        }
    }
    
    public static function __callStatic($method, $arguments)
    {
        $obj = static::singleton();
        if (method_exists($obj, $method)) {
            return call_user_func_array([$obj, $method], $arguments);
        }
    }

    public static function singleton()
    {
        if (static::$obj == null) {
            static::$obj = new static();
        }
        return static::$obj;
    }
}